package cn.bob.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

/**
 * @author bob
 * @data 2022/11/13-10:55
 */
@Component
public class SpringCloudZuulFilter extends ZuulFilter {


    @Override
    public String filterType() {  //前置过滤器
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     *
     * @return
     */
    @Override
    public boolean shouldFilter() {
        //获取request请求中的hander头 其中的uri信息
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        String requestURI = request.getRequestURI();
        //路径中是在登录和注册页面中返回false  不执行 run方法
        if (requestURI.endsWith("/login") || requestURI.endsWith("/register")){
            return false;
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //获取到请求
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        //获取响应
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
        //获取到请求头中的token
        String token = request.getHeader("token");
        //判断token是否存在 不存在直接响应
        if (StringUtils.isEmpty(token)){
            HashMap<String, Object> map = new HashMap<>();
            map.put("success",false);
            map.put("message","请登录！");
            map.put("resultObj","onLogin");
            //有返回中文 需设置响应的字符集
            response.setContentType("application/json;charset=utf-8");
            try {
                //将map转换为字符串响应给前端
                String mapjson = JSON.toJSONString(map);
                PrintWriter writer = response.getWriter();
                writer.write(mapjson);
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //没登陆就直接返回不通过路由拦截
            RequestContext.getCurrentContext().setSendZuulResponse(false);
        }
        return null;
    }
}
